<template>
  <div class="com-container">
    <div class="com-chart" ref="safety_ref"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      intervalId: null, //用于存储计时器ID
      chartInstance: null,
      allData: null
    }
  },
  mounted() {
    this.initChart()
    this.getData()
    this.intervalId = setInterval(this.getData, 10000)
  },
  beforeDestroy() {
    // 在组件销毁之前清除计时器
    if (this.intervalId) {
      clearInterval(this.intervalId)
    }
  },
  methods: {
    initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.safety_ref)
      const initOption = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255,255,255,0.2)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#FF8C00'
            }
          }
        },
        legend: {
          data: ['隐患排查数量', '隐患处理数量', '安全演练次数'],
          textStyle: {
            color: '#B4B4B4'
          },
          top: '0%'
        },
        xAxis: {
          type: 'category',
          axisLine: {
            lineStyle: {
              color: '#B4B4B4'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: [
          {
            splitLine: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: '#B4B4B4'
              }
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              formatter: '{value} '
            }
          },
          {
            splitLine: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: '#B4B4B4'
              }
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              formatter: '{value} '
            }
          }
        ],
        series: [
          {
            name: '安全演练次数',
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                color: '#FF8C00'
              }
            }
          },
          {
            name: '隐患处理数量',
            type: 'bar',
            barWidth: 16,
            itemStyle: {
              normal: {
                barBorderRadius: [8, 8, 0, 0],
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#F0E68C' },
                  { offset: 1, color: '#DAA520' }
                ])
              }
            }
            // label: {
            //   show: true,
            //   position: 'top',
            //   textStyle: {
            //     color: '#B4B4B4'
            //   }
            // }
          },
          {
            name: '隐患排查数量',
            type: 'bar',
            barGap: '-100%',
            barWidth: 16,
            itemStyle: {
              normal: {
                barBorderRadius: [8, 8, 0, 0],
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(255, 255, 102, 0.555)' },
                  { offset: 0.1, color: 'rgba(255, 204, 51, 0.5)' },
                  { offset: 1, color: 'rgba(255, 153, 51, 0.2)' }
                ])
              }
            },
            z: -12
            // label: {
            //   show: true,
            //   position: 'top',
            //   textStyle: {
            //     color: '#B4B4B4'
            //   }
            // }
          }
        ]
      }
      this.chartInstance.setOption(initOption)
    },
    //获取服务器的数据
    async getData() {
      const ret = await this.$http.get('http://localhost:9999/production_line/api/safety/all')
      // console.log(ret.data)
      // 按时间排序，从旧到新
      const sortedData = ret.data.sort((a, b) => new Date(a.safetyTime) - new Date(b.safetyTime))
      // 取最近的12个数据（保证最新的在最后一个）
      const recent12Data = sortedData.slice(-12)
      this.allData = recent12Data
      // console.log(this.allData)
      this.updateChart()
    },
    //更新图表
    updateChart() {
      // const month = []
      // const plannedHandle = []
      // const actualHandle = []
      // this.allData.forEach(item => {
      //   const {
      //     name,
      //     value: { inspect_count, handle_count }
      //   } = item
      //   month.push(name)
      //   plannedHandle.push(inspect_count)
      //   actualHandle.push(handle_count)
      // })
      // const completeRate = actualHandle.map((handle_count, index) => {
      //   const rate = handle_count / plannedHandle[index]
      //   return parseFloat(rate.toFixed(2))
      // })
      const month = this.allData.map(item => {
        const date = new Date(item.safetyTime)
        const year = date
          .getFullYear()
          .toString()
          .slice(2) // 获取年份后两位
        const month = (date.getMonth() + 1).toString().padStart(2, '0') // 获取月份并确保两位数
        return `${year}.${month}`
      })
      const plannedHandle = this.allData.map(item => item.inspectCount)
      const actualHandle = this.allData.map(item => item.handleCount)
      const safetyDrill = this.allData.map(item => item.safetyDrill)
      // console.log(month, plannedHandle, actualHandle, safetyDrill)
      const dataOption = {
        xAxis: {
          data: month
        },
        series: [
          {
            data: safetyDrill
          },
          {
            data: actualHandle
          },
          {
            data: plannedHandle
          }
        ]
      }
      this.chartInstance.setOption(dataOption)
    }
  }
}
</script>

<style>
/* body {
  background-color: #fadd69;
} */
</style>
